package it.webrules.deploymanager.core.hook;

import it.webrules.deploymanager.core.condition.ConditionsEngine;
import it.webrules.deploymanager.core.dy.ApplicationServerConnection;
import it.webrules.deploymanager.core.dy.DeployConditionEngine;
import it.webrules.deploymanager.core.dy.deploy.MBeanManager;
import it.webrules.xsd.dmc.config.v1.Action;
import it.webrules.xsd.dmc.config.v1.CombineCondition;
import it.webrules.xsd.dmc.config.v1.GeneralConfig;
import it.webrules.xsd.dmc.config.v1.Hook;
import it.webrules.xsd.dmc.config.v1.If;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HandleHook {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	public void manageHook(GeneralConfig generalConfig, ApplicationServerConnection serverConnection, Hook hook) {

		HandleHookAction action = new HandleHookAction();

		List<If> ifs = hook.getIf();
		for (If ifBlock : ifs) {

			try {

				if (condifionAreSatisfied(ifBlock.getConditions(), serverConnection.getMBeanManager())) {

					logger.debug("Condition for '{}' are satisfied, exec actions", ifBlock.getName());
					action.doAction(generalConfig, serverConnection, ifBlock.getActions());

				} else {
					logger.debug("Condition for '{}' aren't satisfied.", ifBlock.getName());
				}

			} catch (Exception e) {
				logger.error("If failed.", e);
			}
		}

		List<Action> actions = hook.getAction();
		for (Action act : actions) {
			logger.debug("Exec actions '{}'.", action.getClass().getName());
			action.doAction(generalConfig, serverConnection, act);
		}

	}

	private boolean condifionAreSatisfied(CombineCondition conditions, MBeanManager mbeanManager) throws Exception {
		DeployConditionEngine conditionEngine = new DeployConditionEngine(mbeanManager);
		ConditionsEngine conditionsEngine = new ConditionsEngine(conditionEngine);
		return conditionsEngine.elabConditions(conditions);
	}

}
